import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { GoodsService, GoodsModel } from './customer-good.service';
import { PagedResultDto } from '@abp/ng.core';

@Component({
  selector: 'app-goods-select-dialog',
  templateUrl: './goods-select-dialog.component.html',
  standalone: true,
  imports: [CommonModule, FormsModule]
})
export class GoodsSelectDialogComponent implements OnInit {
  goods: GoodsModel[] = [];
  totalCount = 0;
  page = 1;
  pageSize = 10;
  filter: any = {};

  selected: GoodsModel | null = null;
  loading = false;

  constructor(
    public modal: NgbActiveModal,
    private goodsService: GoodsService
  ) {}

  ngOnInit() {
    this.loadData();
  }

  loadData() {
    this.loading = true;
    this.goodsService.getList({
      skipCount: (this.page - 1) * this.pageSize,
      maxResultCount: this.pageSize,
      ...this.filter
    }).subscribe({
      next: (res: PagedResultDto<GoodsModel>) => {
        this.goods = res.items;
        this.totalCount = res.totalCount;
        this.loading = false;
      },
      error: () => {
        this.loading = false;
      }
    });
  }

  search() {
    this.page = 1;
    this.loadData();
  }

  select(row: GoodsModel) {
    this.selected = row;
  }

  confirm() {
    if (this.selected) {
      this.modal.close(this.selected);
    }
  }

  cancel() {
    this.modal.dismiss();
  }

  onPageChange(newPage: number) {
    this.page = newPage;
    this.loadData();
  }

  reset() {
    this.filter = {};
    this.page = 1;
    this.loadData();
  }
}
